import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @Description 连接数据库
 * @Author zzj
 * @Date 2020/7/22 14:14
 */
public class DBUtil {
    private Connection conn = null;
    private String driverClassName = "oracle.jdbc.OracleDriver";
    private String url = "jdbc:oracle:thin:@192.168.45.129:1521:helowin";
    private String username = "scott";
    private String passwd = "123456";


    // 连接数据库
    public Connection init() {
        try {
            // 加载驱动
            Class.forName(driverClassName);
            // 如果没有连接或者连接关闭，才新建一个数据库连接
            // 避免了数据库连接明明开着却又要新建连接
            if (conn == null || conn.isClosed()) {
                conn = DriverManager.getConnection(url, username, passwd);
            }
            System.out.println("数据库连接成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    // 关闭数据库
    public void close() {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public void setAutoCommit(Boolean flag) {
        try {
            conn.setAutoCommit(flag);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }


}
